<template>
  <div class="comment-view">
    <u-comment
      :config="config"
      :show-size="2"
      page
      style="width: 820px; margin-left: 2rem"
      @submit="submit"
      @like="like"
      @reply-page="replyPage"
      @get-user="getUser"
      @remove="remove"
      @report="report"
    >
      <!-- <template #list-title>全部评论</template> -->
      <template #userInfo>
        <div class="user-card">
          <div class="user-avatar">
            <el-avatar style="margin-top: 5px" :size="40" fit="cover" :src="userInfo.avatar">
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
            </el-avatar>
          </div>
          <div class="user-content">
            <div class="user-info">
              <a href="" class="username" target="_blank">
                <span class="name" style="max-width: 10em">{{ userInfo.username }}</span>
                <span blank="true" class="rank">
                  <u-icon size="24" v-html="useLevel(userInfo.level)"></u-icon>
                </span>
              </a>
            </div>
            <div class="social-info">
              <a href="" class="attention">
                <span>{{ userInfo.attention }}</span>
                <span>关注</span>
              </a>
              <a href="" class="follower">
                <span>{{ userInfo.follower }}</span>
                <span>粉丝</span>
              </a>
              <a href="" class="like">
                <span>{{ userInfo.like }}</span>
                <span>获赞</span>
              </a>
            </div>
            <div class="card-btn">
              <el-button type="primary">关注</el-button>
              <el-button>发消息</el-button>
            </div>
          </div>
        </div>
      </template>
    </u-comment>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { UToast, ConfigApi, CommentApi, useLevel, ReplyPageParam, CommentSubmitParam } from 'undraw-ui'
// 下载表情包资源emoji.zip https://gitee.com/undraw/undraw-ui/releases
// static文件放在public下,引入emoji.ts文件可以移动到自定义位置
import emoji from '@/assets/emoji'
import { ElAvatar, ElButton, UComment, UIcon } from 'undraw-ui'
import { Acomment } from '@/api'

defineOptions({
  name: 'comment'
})
const config = reactive<ConfigApi>({
  user: {
    id: 1,
    username: '',
    avatar: 'https://static.juzicon.com/avatars/avatar-200602130320-HMR2.jpeg?x-oss-process=image/resize,w_100',
    // 评论id数组 建议:存储方式用户id和文章id和评论id组成关系,根据用户id和文章id来获取对应点赞评论id,然后加入到数组中返回
    likeIds: []
  },
  emoji: emoji,
  comments: []
})

const userInfo = ref({} as any)

// 请求获取用户详细信息
const getUser = (uid: string, show: Function) => {
  console.log('获取用户信息: ' + uid)
  setTimeout(() => {
    userInfo.value = {
      id: String(uid),
      username: '落🤍尘',
      avatar: 'https://static.juzicon.com/avatars/avatar-200602130320-HMR2.jpeg?x-oss-process=image/resize,w_100',
      level: 6,
      like: 36011,
      attention: 15,
      follower: 6878
    }
    show()
  }, 0)
}

function toFormData(object: any) {
  const formData = new FormData()
  Object.keys(object).forEach(key => {
    const value = object[key]
    if (Array.isArray(value)) {
      value.forEach((subValue, i) => formData.append(key + `[${i}]`, subValue))
    } else {
      formData.append(key, object[key])
    }
  })
  return formData
}

/**
 * 去除属性值为 null和undefined、''的数据
 * @param obj
 */
function removeEmptyField(obj: any) {
  return Object.keys(obj)
    .filter(key => obj[key] !== null && obj[key] !== undefined && obj[key] !== '')
    .reduce((acc, key) => ({ ...acc, [key]: obj[key] }), {})
}

// 提交评论事件
const submit = ({ content, parentId, files, finish }: CommentSubmitParam) => {
  console.log('提交评论: ' + content, parentId)
  const formData = {
    articleId: 1,
    content: content,
    parentId: parentId,
    files: files
  }
  Acomment.save(toFormData(removeEmptyField(formData))).then(res => {
    finish(res.data as any)
    UToast({ message: '评论成功!', type: 'info' })
  })
}

// 删除评论
const remove = (id: string, finish: () => void) => {
  console.log('删除评论: ' + id)
  setTimeout(() => {
    finish()
    alert(`删除成功: ${id}`)
  }, 200)
}

//举报用户
const report = (id: string, finish: () => void) => {
  console.log('举报用户: ' + id)
  setTimeout(() => {
    finish()
    alert(`举报成功: ${id}`)
  }, 200)
}

// 点赞按钮事件
const like = (id: string, finish: () => void) => {
  console.log('点赞: ' + id)
  Acomment.liked({ articleId: 1, commentId: id }).then(res => {
    finish()
  })
}

//回复分页
const replyPage = ({ parentId, pageNum, pageSize, finish }: ReplyPageParam) => {
  Acomment.replyPage({ url: `/${pageNum}/${pageSize}`, parentId: parentId }).then(res => {
    finish(res.data)
  })
}

onMounted(() => {
  Acomment.list({ url: `/1/5`, articleId: 1 }).then(res => {
    config.comments = res.data
  })
  Acomment.cidList({ url: `/${config.user.id}` }).then(res => {
    config.user.likeIds = res.data
  })
})
</script>

<style lang="scss" scoped>
.user-card {
  display: flex;
  .user-content {
    flex: 1;
    margin-left: 16px;
    .user-info {
      .username {
        display: flex;
        align-items: center;
        text-decoration: none;
        .name {
          max-width: 10rem;
          font-weight: 500;
          font-size: 15px;
          color: #252933;
          line-height: 32px;
          margin-right: 4px;
        }
      }
    }
    .social-info {
      margin-bottom: 10px;
      a {
        text-decoration: none;
      }
      a:not(:first-child) {
        margin-left: 18px;
      }
      a span:last-child {
        margin-left: 3px;
        color: #9499a0;
      }
    }
  }
}
</style>
